﻿Imports System.Collections.Specialized.BitVector32
Imports AutoCAD

''' <summary>
''' CAD绘制开槽服务
''' </summary>
Public Class CadDrawSlotServiceImpl
    Private ms As IAcadBlock

    ''' <summary>
    ''' 在平面上开槽, 指定槽宽度及启点终点, 返回槽对象
    ''' </summary>
    ''' <param name="startPoint"> 启点 </param>
    ''' <param name="endPoint"> 终点 </param>
    ''' <param name="width"> 槽宽 </param>
    ''' <param name="depth"> 槽深 </param>
    ''' <param name="elevation"> 高程, 决定开槽轮廓线坐在位置, 大于0则向下开槽, 否则向上开槽 </param>
    ''' <returns></returns>
    Public Function drawFlatSlot(ByRef startPoint As Double(), ByRef endPoint As Double(), ByVal width As Double, ByVal depth As Double, ByRef elevation As Double) As Acad3DSolid
        Dim lineLength As Double = Math.Sqrt((endPoint(0) - startPoint(0)) ^ 2 + (endPoint(1) - startPoint(1)) ^ 2)

        ' 计算两点之间的单位向量
        Dim dx = (endPoint(0) - startPoint(0)) / lineLength
        Dim dy = (endPoint(1) - startPoint(1)) / lineLength

        ' 计算垂直于两点连线的单位向量
        Dim perp_dx = -dy
        Dim perp_dy = dx

        ' 计算四点坐标
        Dim halfWidth As Double = width / 2
        Dim p(7) As Double
        p(0) = startPoint(0) - halfWidth * perp_dx : p(1) = startPoint(1) - halfWidth * perp_dy
        p(2) = startPoint(0) + halfWidth * perp_dx : p(3) = startPoint(1) + halfWidth * perp_dy
        p(4) = endPoint(0) + halfWidth * perp_dx : p(5) = endPoint(1) + halfWidth * perp_dy
        p(6) = endPoint(0) - halfWidth * perp_dx : p(7) = endPoint(1) - halfWidth * perp_dy

        ' 绘制多段线
        Dim pl As AcadLWPolyline = ms.AddLightWeightPolyline(p)
        pl.Closed = True
        pl.Elevation = elevation

        ' 拉伸
        Dim objectList() As AcadEntity = New AcadEntity() {pl}
        Dim region = ms.AddRegion(objectList) '面域
        Dim sld As Acad3DSolid = ms.AddExtrudedSolid(region(0), IIf(elevation > 0, depth * -1, depth), 0)
        region(0).delete

        ' 返回对象
        Return sld
    End Function

#Region "TEST"
    Public Sub test2()
        Dim cadApplicationService As ICadApplicationService = New CadApplicationServiceImpl
        Dim doc As AcadDocument = cadApplicationService.GetActiveDocument
        Me.ms = doc.ModelSpace
        drawFlatSlot(New Double() {5, 0}, New Double() {5, -300}, 10, 5, 25)
    End Sub
#End Region

End Class
